import {routes, layoutRouter, managerRouter, spManagerRouter, spmRouter} from '../../router/index'

const router = {
    state: {
        dynamic: {}, // 动态路由集
        routerChange: false
    },

    mutations: {
        UPDATE_ROUTERS: (state, list) => {
            // 标记路由已动态更改
            state.routerChange = true
        },
        ADD_DYNAMIC: (state, list) => {
            // 将动态路由赋值给dynamic对象，方便组件中获取数据
            state.dynamic.layoutRouter = layoutRouter
            state.dynamic.managerRouter = managerRouter
            state.dynamic.spManagerRouter = spManagerRouter
            state.dynamic.spmRouter = spmRouter
        }
    },

    actions: {
        generateRouters({commit}, user) {
            // 动态添加路由
            return new Promise((resolve, reject) => {
                commit('ADD_DYNAMIC')
                let routeList = [] // 即将动态添加的路由集
                if (!user || !user.bmanager) {
                    // 普通账户
                    layoutRouter.forEach(function (item, index, arr) {
                        routes[0].children.unshift(...item.children)
                    })
                    routeList.push(routes[0])
                } else if (user.bmanager === 1) {
                    // 机构管理员账户
                    managerRouter.forEach(function (item, index, arr) {
                        routes[1].children.unshift(...item.children)
                    })
                    routes[3].children.push(...spmRouter)
                    routeList.push(routes[1], routes[3])
                } else {
                    // 超级管理员账户
                    routes[2].children.push(...spManagerRouter)
                    routes[3].children.push(...spmRouter)
                    routeList.push(routes[2], routes[3])
                }
                resolve(routeList)
            })
        },
        generateAllRouters({commit}, user) {
            // 动态添加所有的路由
            return new Promise((resolve, reject) => {
                commit('ADD_DYNAMIC')
                let routeList = [] // 即将动态添加的路由集
                layoutRouter.forEach(function (item, index, arr) {
                    routes[0].children.unshift(...item.children)
                })
                managerRouter.forEach(function (item, index, arr) {
                    routes[1].children.unshift(...item.children)
                })
                spManagerRouter.forEach(function (item, index, arr) {
                    routes[2].children.unshift(...item.children)
                })
                // routes[2].children.push(...spManagerRouter)
                routes[3].children.push(...spmRouter)
                routeList.push(...routes)
                resolve(routeList)
            })
        },
        updateRouters({commit}) {
            commit('UPDATE_ROUTERS')
        }
    }
}

export default router
